﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace PMOMEventReceivers.EventReceiver1
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class EventReceiver1 : SPItemEventReceiver
    {
        private readonly string[] monthNames = new string[] {"January", "February", "March",
                                                             "April", "May", "June",
                                                             "July", "August", "September",
                                                             "October", "November", "December"};
        /// <summary>
        /// An item is being added.
        /// </summary>
        public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
        }

        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            //Get Project.Client.agency.agreedhourlyrate
            SPFieldLookupValue clientLookupVal = new SPFieldLookupValue(Convert.ToString(properties.ListItem[Constants.FieldClient]));
            SPListItem clientListItem = properties.Web.Lists[Constants.ListTitleClients].GetItemById(clientLookupVal.LookupId);
            SPFieldLookupValue parentAgencyLookupVal = new SPFieldLookupValue(Convert.ToString(clientListItem[Constants.FieldParent]));
            SPListItem agencyListItem = properties.Web.Lists[Constants.ListTitleAgencies].GetItemById(parentAgencyLookupVal.LookupId);

            object hourlyRateObj = agencyListItem[Constants.FieldAgreedHourlyRate];
            if (hourlyRateObj != null)
            {
                int agencyAgreedHourlyRate = Convert.ToInt32(hourlyRateObj);
                // make the project.agreedhourlyrate = agencyHourlyRate
                using (new DisabledItemEventsScope())
                {
                    SPListItem thisCurrentItem = properties.List.GetItemById(properties.ListItemId);

                    thisCurrentItem[Constants.FieldAgreedHourlyRate] = agencyAgreedHourlyRate;
                    thisCurrentItem.SystemUpdate(false);
                }
            }

            
            //get Project.NumberOfHours
            int numOfHours = Convert.ToInt32(properties.ListItem[Constants.FieldNumberofHoursDisplayName]);
            
            //Get the end date and start date
            DateTime endDate = Convert.ToDateTime(properties.ListItem[Constants.FieldEndDate]);
            DateTime startDate = Convert.ToDateTime(properties.ListItem[Constants.FieldStartDate]);

            //Get Project.Client.Advertiser.Contractor.ContractorUser
            SPFieldLookupValue childAdvertiserLookupVal = new SPFieldLookupValue(Convert.ToString(clientListItem[Constants.FieldChild]));
            SPListItem advertiserListItem = properties.Web.Lists[Constants.ListTitleAdvertisers].GetItemById(childAdvertiserLookupVal.LookupId);
            SPFieldLookupValue contractorLookupVal = new SPFieldLookupValue(Convert.ToString(advertiserListItem[Constants.FieldContractor]));
            SPListItem contractorListItem = properties.Web.Lists[Constants.ListTitleContractors].GetItemById(contractorLookupVal.LookupId);
            SPUser contractorUser = Utilities.GetSPUser(contractorListItem, Constants.FieldContractorUserDisplayName);

            //is repeating 
            bool isRepeating = Convert.ToBoolean(properties.ListItem[Constants.FieldmonthlyRecurring]);
            SPList taskList = properties.Web.Lists[Constants.ListTitleTasks];
            if (isRepeating)
            {
                // if the item is marked as repeating , then do all funky stuff.                

                ////get year month of both dates. find the number of months between 2 dates
                // (Year2-Year1)*12 + month2-month1+1
                int numOfMonths = (endDate.Year - startDate.Year) * 12 + (endDate.Month - startDate.Month + 1);                

                //Automate creation of project months and tasks.
                for (int i = startDate.Month; i < (startDate.Month + numOfMonths); i++)
                {
                    int monthAdditive = (i - startDate.Month);

                    DateTime startDateForNewProjectMonth = Utilities.FirstDayOfMonthFromDateTime(startDate.AddMonths(monthAdditive));
                    DateTime endDateForNewProjectMonth = Utilities.LastDayOfMonthFromDateTime(startDate.AddMonths(monthAdditive));

                    if (endDateForNewProjectMonth > endDate)
                    {
                        endDateForNewProjectMonth = endDate;
                    }

                    //create Project Months for each month
                    SPList projectMonthsList = properties.Web.Lists[Constants.ListTitleProjectMonths];

                    SPListItem newItem = projectMonthsList.AddItem();
                    newItem["Title"] = properties.ListItem.Title + " - " + monthNames[startDateForNewProjectMonth.Month - 1] + " " + startDateForNewProjectMonth.Year;
                    newItem[Constants.FieldProject] = new SPFieldLookupValue(properties.ListItemId, properties.ListItem.Title);
                    newItem[Constants.FieldStartDate] = startDateForNewProjectMonth;
                    newItem[Constants.FieldEndDate] = endDateForNewProjectMonth;
                    newItem.SystemUpdate(false);

                    //Create one month repeating type task in task list
                    SPListItem taskItem = taskList.AddItem();
                    SPContentType ct = taskList.ContentTypes[Constants.CTMonthlyRepeatingProjectTask];
                    taskItem["Title"] = newItem.Title + " Task 1";
                    taskItem["ContentTypeId"] = ct.Id;
                    taskItem["ContentType"] = ct.Name;
                    taskItem[Constants.FieldStartDate] = startDateForNewProjectMonth;
                    taskItem[Constants.FieldDueDate] = endDateForNewProjectMonth;
                    taskItem[Constants.FieldProjectMonth] = new SPFieldLookupValue(newItem.ID, newItem.Title);
                    if (contractorUser != null)
                    {
                        taskItem[SPBuiltInFieldId.AssignedTo] = contractorUser; //Set the contractor for Project.Client.Advertiser.Contractor.ContractorUser as assigned to
                    }
                    taskItem[Constants.FieldNumberofHoursDisplayName] = numOfHours; //Allocate all the hours to task 1 for this project month.

                    taskItem.SystemUpdate(false);
                }
            }
            else
            {
                //create adhoc task
                //Create one month repeating type task in task list
                SPListItem adhocTaskItem = taskList.AddItem();
                SPContentType ct = taskList.ContentTypes[Constants.CTProjectAdhocTask];
                adhocTaskItem["Title"] =  properties.ListItem.Title + " Adhoc Task 1";
                adhocTaskItem["ContentTypeId"] = ct.Id;
                adhocTaskItem["ContentType"] = ct.Name;
                adhocTaskItem[Constants.FieldStartDate] = startDate;
                adhocTaskItem[Constants.FieldDueDate] = endDate;
                adhocTaskItem[Constants.FieldProjectMonth] = new SPFieldLookupValue(properties.ListItemId, properties.ListItem.Title);
                if (contractorUser != null)
                {
                    adhocTaskItem[SPBuiltInFieldId.AssignedTo] = contractorUser; //Set the contractor for Project.Client.Advertiser.Contractor.ContractorUser as assigned to
                }
                adhocTaskItem[Constants.FieldNumberofHoursDisplayName] = numOfHours; //Allocate all the hours to task 1 for this project month.

                adhocTaskItem.SystemUpdate(false);
            }



            base.ItemAdded(properties);
        }


    }
}
